# -*- coding:utf-8 -*-
#Written by MMCOWBOY
import pygame
import random
import weapon, effect#, flame
import item
import string
import mp_attack

class player_obj(pygame.sprite.Sprite):

    SPARK_INTV = 2
    FIRE_INTV = 4                                           # Fire every 1 frames
    BOMB_INTV = 60
    MATTACK_INTV = 200
    HARM_LAST = 50                                          # How long can player keep in harmless mode
    WEAPON_UPGRADE_LIMIT = 4                                # So far, the weapon can be upgraded 4 times at most
    DEFAULT_HP = 10                                         # initial HP
    DEFAULT_EXP_LIMIT = 500                                 # initial Exp upgrade limit
    
    #-------------------------------------
    DEFAULT_MP = 0                                          # initial MP
    DEFAULT_MP_LIMIT = 100
    DEFAULT_MP_NUM = 0
    DEFAULT_MP_NUM_LIMIT = 3
    DEFAULT_MP_TIME_SCALE = 100
    #----------------------------------------

    TOP_LIMIT = 40                                          # player's rect.top most top
    BOTTOM_LIMIT = 40                                       # player's rect.bottom most bottom
    
    def __init__(self, player_num, player_gui, screen_size, attack_list, mid = True):
        super(player_obj, self).__init__(self.containers)
        
        self.attack_list = attack_list              # player's attack list
        self.screen_width = screen_size[0]		    # screen width
        self.screen_height = screen_size[1]	            # screen height
        self.screen_size = screen_size			    # screen size
        self.hp = self.DEFAULT_HP			    # initialize hp
        self.exp = 0					    # initialize exp
        #----------------------------------------
        self.mp = self.DEFAULT_MP
        self.max_mp = self.DEFAULT_MP_LIMIT
        self.mp_num = self.DEFAULT_MP_NUM
        self.mp_time_scale = self.DEFAULT_MP_TIME_SCALE
        self.is_magic_attack = True
        self.is_be_shooted = False          #用于检测是否玩家被打到
        #----------------------------------------
        self.score = 0					    # initialize score
        self.speed = 5					    # initialize speed
        self.player_num = player_num			    # initialize player's number
        self.lives = 3                                      # default player lives is 3
#        len(self.bomb_list) = 3                                   # default bomb numb is 3
        self.isalive = True                                 # living tag
        self.harm_less = self.HARM_LAST                     # How long can player keep in harmless mode
        self.max_exp = self.DEFAULT_EXP_LIMIT               # Weapon level is upgraded by exp
        self.max_hp = self.DEFAULT_HP			    # HP up limit
        self.weapon_level = 1                               # Default weapon level is 1
        self.flame_spark_intv = self.SPARK_INTV             # trail flame's spark interval
        self.fire_intv = 0       	    		    # initialize fire interval
        self.bomb_intv = 0                          # bomb's (if got any) fire interval
        self.mattack_intv = 0
        self.super_shield = None                            # anemy can't hurt the player but player can crash enemy
        self.additional_weapon = None                        # addtional weapons that obtain by getting items
        self.power = 20
        self.laser_guns = weapon.get_laser_gun(self.weapon_level, self)
        self.bomb_list = [1,1,1]
        
        self.belong_to = None
        
        #---------- playergui ----------
        self.player_gui = player_gui                        # the gui instance that belong to player
        self.player_gui.set_player_info( int(self.hp), int(self.max_hp), int(self.exp), int(self.max_exp),\
                  int(self.mp), int(self.max_mp), int(self.mp_num), int(self.score), int(self.lives), int(len(self.bomb_list)) )
        #-------------------------------
                
        if (self.player_num == 1):
            self.build_player_1(mid)
            
        elif (self.player_num == 2):
            self.build_player_2(mid)
    
    def get_shield(self):
        return self.super_shield
    
    def set_harm_less(self, last_time = 50):
        self.harm_less = last_time
        
    def is_shield(self):
        return not (self.super_shield is None)
    
    def build_player_1(self, mid):
        # 读取上次的设置
        player1_keyboard = {'Up' : pygame.K_w, 'Down' : pygame.K_s, 'Left' : pygame.K_a, 'Right' : pygame.K_d, 'Shoot' : pygame.K_j,\
                    'Bomb' : pygame.K_k, 'Magic_Attack': pygame.K_l, 'Start':pygame.K_1 }
        filename = "data/game.opt"
        file_object = open( filename, 'r' )
        file_lines = file_object.readlines()
        line_index = 0
        for line in file_lines:
            list = line.split(' ')
            if line_index == 2:
                player1_keyboard['Up'] = string.atoi(list[0])
                player1_keyboard['Down'] = string.atoi(list[1])
                player1_keyboard['Left'] = string.atoi(list[2])
                player1_keyboard['Right'] = string.atoi(list[3])
                player1_keyboard['Shoot'] = string.atoi(list[4])
                player1_keyboard['Bomb'] = string.atoi(list[5])
                player1_keyboard['Magic_Attack'] = string.atoi(list[6])
                player1_keyboard['Start'] = string.atoi(list[7])
            line_index += 1

        file_object.close()
        #print "player1"
        self.norm_image = pygame.image.load("data/images/p1.png")
        self.accl_image = pygame.image.load("data/images/p1accel.png")
        self.image = self.norm_image
        self.rect = self.image.get_rect()
        self.up = player1_keyboard['Up']            # up
        self.down = player1_keyboard['Down']          # down
        self.left = player1_keyboard['Left']          # left
        self.right = player1_keyboard['Right']         # right
        self.fire = player1_keyboard['Shoot']      # fire
        self.start = player1_keyboard['Start']         # recover (for test usage)
        self.bomb = player1_keyboard['Bomb']      # bomb fire
        self.magic_attack = player1_keyboard['Magic_Attack']  # magic attack
        if (mid):
            self.rect = self.rect.move(self.screen_width / 2.0 - self.rect.width / 2.0,\
                                        self.screen_height - self.rect.height - self.BOTTOM_LIMIT)
        else:
            self.rect = self.rect.move(self.screen_width / 4.0 - self.rect.width / 2.0,\
                                        self.screen_height - self.rect.height - self.BOTTOM_LIMIT)
        self.init_pos = self.rect.center

    def build_player_2(self, mid):
        # 读取上次的设置
        player2_keyboard = {'Up' : pygame.K_UP, 'Down' : pygame.K_DOWN, 'Left' : pygame.K_LEFT, 'Right' : pygame.K_RIGHT, 'Shoot' : pygame.K_KP1,\
                    'Bomb' : pygame.K_KP2, 'Magic_Attack': pygame.K_KP3, 'Start':pygame.K_2 }
        filename = "data/game.opt"
        file_object = open( filename, 'r' )
        file_lines = file_object.readlines()
        line_index = 0
        for line in file_lines:
            list = line.split(' ')
            if line_index == 3:
                player2_keyboard['Up'] = string.atoi(list[0])
                player2_keyboard['Down'] = string.atoi(list[1])
                player2_keyboard['Left'] = string.atoi(list[2])
                player2_keyboard['Right'] = string.atoi(list[3])
                player2_keyboard['Shoot'] = string.atoi(list[4])
                player2_keyboard['Bomb'] = string.atoi(list[5])
                player2_keyboard['Magic_Attack'] = string.atoi(list[6])
                player2_keyboard['Start'] = string.atoi(list[7])
            line_index += 1

        file_object.close()
        self.norm_image = pygame.image.load("data/images/p2.png")
        self.accl_image = pygame.image.load("data/images/p2accel.png")
        self.image = self.norm_image
        self.rect = self.image.get_rect()
        self.up = player2_keyboard['Up']
        self.down = player2_keyboard['Down']
        self.left = player2_keyboard['Left']
        self.right = player2_keyboard['Right']
        self.fire = player2_keyboard['Shoot']
        self.start = player2_keyboard['Start']
        self.bomb = player2_keyboard['Bomb']
        self.magic_attack = player2_keyboard['Magic_Attack']
        if (mid):
            self.rect = self.rect.move(self.screen_width / 2.0 - self.rect.width / 2.0,\
                                        self.screen_height - self.rect.height - self.BOTTOM_LIMIT)
        else:
            self.rect = self.rect.move(3.0 * self.screen_width / 4.0 - self.rect.width / 2.0,\
                                        self.screen_height - self.rect.height - self.BOTTOM_LIMIT)
        self.init_pos = self.rect.center

    def move(self):
        key = pygame.key.get_pressed()
        if (self.isalive):
            if key[self.up]:
                #print "up"
                if (self.rect.top - self.speed >= self.TOP_LIMIT):
                    self.rect = self.rect.move(0,-self.speed)
                else:
                    self.rect.top = self.TOP_LIMIT
                effect.flame_spot((self.rect.centerx , self.rect.centery + 20), 0, self.speed / 2.0, 5, 50)
            if key[self.down]:
                #print "down"
                if (self.rect.bottom + self.speed < self.screen_height - self.BOTTOM_LIMIT):
                    self.rect = self.rect.move(0,self.speed)
                else:
                    self.rect.bottom = self.screen_height- 1 - self.BOTTOM_LIMIT
            if key[self.left]:
                #print "left"
                if (self.rect.left - self.speed >= 0):
                    self.rect = self.rect.move(-self.speed,0)
                else:
                    self.rect.left = 0
            if key[self.right]:
                #print "right"
                if (self.rect.right + self.speed < self.screen_width):
                    self.rect = self.rect.move(self.speed,0)
                else:
                    self.rect.right = self.screen_width - 1
                    self.rect = self.rect.move(self.screen_width - self.rect.right,0)
            if key[self.fire]:
                if (self.fire_intv == 0):
                    self.fire_laser()
                    self.fire_intv = self.FIRE_INTV
                else:
                    self.fire_intv -= 1
            if key[self.bomb]:
                if (self.bomb_intv == 0):
                    self.fire_bomb()
                    self.bomb_intv = self.BOMB_INTV
                else:
                    self.bomb_intv -= 1

        #-----------------------------------------------             
            if key[self.magic_attack]:
                #self.mp_num = 2
                if self.mp_num == 1:
                    if self.is_magic_attack:
                        mp_attack.missile_magic_attack( self )
                        self.mp_num -= 1             
                if self.mp_num == 2:
                    if self.is_magic_attack:
                        mp_attack.steal_magic_attack( self )
                        self.mp_num -= 2
                if self.mp_num == 3:
                    if self.is_magic_attack:
                        self.fire_bt_laser()
                        self.mp_num -= 3


                self.is_magic_attack = False
                #return 
                print "magic attack!!"

            if not key[self.magic_attack]:
                self.is_magic_attack = True
        else:
            if key[self.start]:
#                self.recover()
                pass
    
        #--------------------------------------------    
        pass

    def is_alived(self):
        return self.isalive

    def is_harm_less(self):
        return self.harm_less

    def reset_pos(self):
        self.harm_less = self.HARM_LAST
        self.rect.center = self.init_pos
        if (self.super_shield):
            self.super_shield.kill()
            self.super_shield = None                            # anemy can't hurt the player but player can crash enemy
        if (self.additional_weapon):
            self.additional_weapon.kill()
            self.additional_weapon = None                        # addtional weapons that obtain by getting items

    def recover(self):

        self.isalive = True
        self.reset_pos()
        self.hp = self.max_hp
        self.laser_guns = weapon.get_laser_gun(self.weapon_level, self)

    def destroied(self, opponent): #called by the shot that hit the obj
        #-------------------------------------
        return
        self.mp = self.DEFAULT_MP   #mp归零
        if self.mp_num > 0:         #mp_num特技数减1
            self.mp_num -= 1
        self.mp_time_scale = 0

        self.is_be_shooted = True   #玩家被打到
        #------------------------------------
        self.hp -= opponent.power
        if (self.hp <= 0):
            self.crashed()

    def crashed(self):

        #-------------------------------------
        self.mp = self.DEFAULT_MP                #mp归零                
        self.mp_num  = self.DEFAULT_MP_NUM            #mp_num特技数归零
        self.mp_time_scale = 0
        #--------------------------------------

        self.hp = 0
        self.isalive = False
        
        explos_sound = pygame.mixer.Sound("data/sounds/explos_player.wav")
        explos_sound.set_volume(1.0)
        explos_sound.play()
        
        
        if (self.lives):
            self.lives -= 1
            print "1: ",self.lives
            if (self.weapon_level > 1):
                self.weapon_level -= 1
            self.player_gui.set_player_info( int(self.hp), int(self.max_hp), int(self.exp), int(self.max_exp),\
                  int(self.mp), int(self.max_mp), int(self.mp_num), int(self.score), int(self.lives), int(len(self.bomb_list)) )
            self.player_gui.update()
#            flame.explosion(self.rect.center, 50)
            #------------------player crashed flame----------------------
            effect.spark_obj(self.rect.center)
            #flame...
            if (self.lives):
        #-----------------------------------------------------
                self.bomb_list = [1,1,1]
                print "bll: ",len(self.bomb_list)
        #-----------------------------------------------------
                self.recover()
            else:
                self.kill()

    def draw(self, screen):
        if (self.isalive):                      #display the player if still alive
            if (not (self.harm_less % 4)):      #blink when harmless
                screen.blit(self.image, self.rect)

    def fire_bomb(self):
        if (len(self.bomb_list)):
            weapon.get_bomb(self.bomb_list[-1], self)
            del(self.bomb_list[-1])

    def fire_laser(self):
        if (self.laser_guns):
            self.laser_guns.fire()
            
    def fire_bt_laser(self):
        mp_attack.bt_laser_gun(self, 0, 8) 
        mp_attack.bt_laser_gun(self, 120, 8) 
        mp_attack.bt_laser_gun(self, 240, 8) 
        self.mattack_intv = self.MATTACK_INTV
              
            
    def weapon_can_up(self):
        return (self.weapon_level < self.WEAPON_UPGRADE_LIMIT)

    def exp_update(self):
        while (self.exp >= self.max_exp):
            print "UpGrade!"
            if (self.weapon_can_up()):
                self.weapon_level += 1
                self.laser_guns = weapon.get_laser_gun(self.weapon_level, self)
            self.exp -= self.max_exp
            self.max_exp *= 2
            self.max_hp *= 2
            self.hp = self.max_hp
            self.lives += 1
            
    def update(self):
        if (self.flame_spark_intv == 0):
            self.flame_spark_intv = self.SPARK_INTV
            self.image = self.accl_image
        else:
            self.flame_spark_intv -= 1
            self.image = self.norm_image
        if (self.harm_less):
            self.harm_less -= 1
        if (self.bomb_intv):
            self.bomb_intv -= 1

        #----------------------------------------------
        if self.mp_time_scale > 0:
            self.mp_time_scale -= 3
        if self.mp_time_scale < 0:
            self.mp_time_scale = 0    
        #print self.mp_num
        #------------------------------------------
        self.move()
        self.player_gui.set_player_info( int(self.hp), int(self.max_hp), int(self.exp), int(self.max_exp),\
                  int(self.mp), int(self.max_mp), int(self.mp_num), int(self.score), int(self.lives), int(len(self.bomb_list)) )
        self.player_gui.update()

        
        
       

